package com.celi.system.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.celi.cii.base.ResponseDTO;
import com.celi.system.entity.UserLoginEntity;
import com.celi.system.service.OAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * @Author jiangshengjun
 * @Date 2024/8/16
 * @Description
 */

@RestController
@RequestMapping({"${url.prefix}/oauth"})
public class OAuthController {
    @Autowired
    private OAuthService oAuthService;

    public OAuthController() {
    }

    @PostMapping({"/login"})
    public ResponseDTO userLogin(@RequestBody UserLoginEntity userLoginEntity) {
        this.oAuthService.userLogin(userLoginEntity);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return ResponseDTO.ok(tokenInfo.tokenValue);
    }

    @GetMapping({"/userInfo"})
    public ResponseDTO userInfo() {
        String userId = StpUtil.getLoginIdAsString();
        return ResponseDTO.ok(this.oAuthService.queryUserInfo(userId));
    }

    @GetMapping({"/logout"})
    public ResponseDTO userLogOut(@RequestParam(required = false,defaultValue = "PC") String loginType) {
        try {
            StpUtil.logout(StpUtil.getLoginId(), loginType);
        } catch (NotLoginException e) {
            StpUtil.logout();
        }
        return ResponseDTO.ok();
    }

    @GetMapping({"/userMenus"})
    public ResponseDTO queryUserMenu() {
        return ResponseDTO.ok(this.oAuthService.userPermissionByGroup());
    }

    @GetMapping({"/userFlatMenus"})
    public ResponseDTO queryUserFlatMenu() {
        return ResponseDTO.ok(this.oAuthService.userPermissionFlatByGroup());
    }

    @GetMapping({"/listPermissionsByUser"})
    public ResponseDTO listPermissionsByUser() {
        return ResponseDTO.ok(this.oAuthService.listPermissionsByUser());
    }
}
